__author__ = 'tyrion'

from flask import  Flask, abort
from flask import request
# from  conf.gloal import PLUGIN_TYPE
from conf.gloal import *


import  json
import  importlib

from src.ConfMgr import GetInstancesDetail

app = Flask(__name__)




@app.route("/infrastructure/monitor/server/delete", methods=['GET', 'POST'])
def DeleteMachine():
    #[{"type: "Tomcat", "hostname": "myhostname", "ip":"172.24.133.41"}]
    data = request.get_data()
    print"info: request body = %s" %(data)
    machines = json.loads(data)

    retList = []

    for machine in machines:

        type = machine.get("type", "error: not found instance type")
        pluginModuleName = "src.CreateItemPlugins.%s" % (type)
        print pluginModuleName
        pluginModule = importlib.import_module(pluginModuleName)
        pluginClassName = PLUGINS.get(type)
        print("info:pluginClassName=%s "%pluginClassName)
        pluginClass = getattr(pluginModule, pluginClassName)
        conf = {}
        conf['hostname'] = machine.get('hostname')
        conf['ip'] = machine.get('ip')
        conf['ports'] = ""
        conf['place'] = machine.get("place")
        conf['env'] = machine.get("env")
        plugin = pluginClass(conf)

        ret = {"host": machine.get("hostname")}

        ret1 = plugin.DeleteMachine()
        if ret1 != 200:
            msg1 = "delete machine failed"
            ret["status"] = "failed"
            ret["msg"] = msg1
        else:
            msg1 = "delete machine successfull"

            ret2 = plugin.ReloadConf(REAL_ICINGA_SERVER.get(plugin.GetKey()), REAL_SALT_MATER.get(plugin.GetKey()))
            if ret2 != 200:
                msg2 = "monitor server reload config failed"
                ret["status"] = "failed"
                ret["msg"]  = "%s,%s"%(msg1, msg2)
            else:
                msg2 = "monitor server reload conifg sucessfull"
                ret["status"] = "successful"
                ret["msg"]  = "%s,%s"%(msg1, msg2)

        retList.append(ret)
    return json.dumps(retList)


@app.route("/infrastructure/monitor/server/add", methods=['GET', 'POST'])
def AddMachine():
    #[{"type: "Tomcat", "hostname": "myhostname", "ip":"172.24.133.41"}]
    data = request.get_data()
    print"info: request body = %s" %(data)
    machines = json.loads(data)

    retList = []

    for machine in machines:

        type = machine.get("type", "error: not found instance type")
        pluginModuleName = "src.CreateItemPlugins.%s" % (type)
        print pluginModuleName
        pluginModule = importlib.import_module(pluginModuleName)
        pluginClassName = PLUGINS.get(type)
        print("info:pluginClassName=%s "%pluginClassName)
        pluginClass = getattr(pluginModule, pluginClassName)
        conf = {}
        conf['hostname'] = machine.get('hostname')
        conf['ip'] = machine.get('ip')
        conf['ports'] = ""
        conf['place'] = machine.get("place")
        conf['env'] = machine.get("env")
        plugin = pluginClass(conf)

        ret = {"host": machine.get("hostname")}

        ret1 = plugin.CreateMachine()
        if ret1 != 200:
            msg1 = "create machine failed"
            ret["status"] = "failed"
            ret["msg"] = msg1
        else:
            msg1 = "create machine successfull"
            if plugin.CreateMonitors():
                msg3 = "create monitors failed"
            else:
                msg3 = "create monitors sucessfull"
            ret2 = plugin.AddToMonitorSvr()
            if ret2 != 200:
                msg2 = "monitor server reload config failed"
                ret["status"] = "failed"
                ret["msg"]  = "%s,%s"%(msg1, msg2)
            else:
                msg2 = "monitor server reload conifg sucessfull"
                ret["status"] = "successful"
                ret["msg"]  = "%s,%s,%s"%(msg1, msg3, msg2)
        retList.append(ret)

    return json.dumps(retList)



@app.route("/instance", methods=['GET', 'POST'])
def AddInstances():

    data = request.get_data()
    print"info: request body = %s" %(data)
    severs = json.loads(data)
    for svrName in severs:

    # svrName = request.args.get('svrname', "error: not found svrName")
        print("info: server name is %s" %(svrName))
        AddInstancesIntoMonitor(svrName)
    return "add instance into monitor ok"


def AddInstancesIntoMonitor(svrName):

    instances = GetInstancesDetail(svrName)
    print("info: get instances config ret = %s" % json.dumps(instances))
    for instance in instances:
        type = instance.get("type", "error: not found instance type")
        realType = PLUGIN_TYPE.get(type, "error: not found instance real type")

        pluginModuleName = "src.CreateItemPlugins.%s" % (realType)
        print pluginModuleName
        pluginModule = importlib.import_module(pluginModuleName)
        pluginClassName = PLUGINS.get(realType)
        print("info:pluginClassName=%s "%pluginClassName)
        pluginClass = getattr(pluginModule, pluginClassName)
        plugin = pluginClass(instance)
        plugin.CreateMonitors()
        plugin.AddToMonitorSvr()



def InitPluginType():
    #todo
    return


if __name__ == "__main__":
    # AddInstancesIntoMonitor("TEST HOST")
    app.run(debug = True, host="0.0.0.0", port=5002)
